package com.nh.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.nh.mapper.UserMapper;
import com.nh.po.User;
import com.nh.po.UserExample;
import com.nh.service.UserService;
import com.nh.util.PageResult;
import com.nh.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public List<User> findAll() {
        return userMapper.selectAll();
    }

    @Override
    public PageResult<User> findByPage(Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);
        List<User> users = this.findAll();
        Page<User> userPage = (Page<User>) users;
        return  new PageResult<>(userPage.getResult(),userPage.getTotal());
    }

    @Override
    public PageResult<User> search(Integer page, Integer pageSize, UserVo userVo) {
        PageHelper.startPage(page,pageSize);
        if (userVo != null){
            UserExample userExample = new UserExample();
            UserExample.Criteria criteria = userExample.createCriteria();
            if(StrUtil.isNotBlank(userVo.getName())){
                criteria.andNameLike("%" + userVo.getName() + "%");
            }
            if(userVo.getSex() != null){
                criteria.andSexEqualTo(userVo.getSex());
            }
            List<User> users = userMapper.selectByExample(userExample);
            Page<User> userPage = (Page<User>) users;

            return  new PageResult<>(userPage.getResult(),userPage.getTotal());
        }else{
            List<User> users = this.findAll();
            Page<User> userPage = (Page<User>) users;
            return  new PageResult<>(userPage.getResult(),userPage.getTotal());}
    }

    @Override
    public boolean save(User user) {
        return userMapper.insert(user) > 0;
    }
}
